// 导入云对象
const BGToken = uniCloud.importObject("bg-token")

export const getAccessToken = async () => {

	// 从本地存储获取token
	let ttToken = uni.getStorageSync("tt-token")

	if (ttToken) {

		let expiresAt = ttToken.expiresAt;

		let now = Date.now()

		if (now < expiresAt * 1000) {
			return ttToken.access_token
		} else {
			const res = await BGToken.get()
			uni.setStorageSync("tt-token", res)
			return res.access_token;
		}



	} else {
		const res = await BGToken.get()

		uni.setStorageSync("tt-token", res)

		return res.access_token;

	}

}

const SecurityAPI = "https://developer.toutiao.com/api/v2/tags/text/antidirt"

export const useSecurity = async (tasks) => {

	const access_token = await getAccessToken()

	if (!access_token) {
		return
	}

	return new Promise(async (resolve, reject) => {

		uni.request({
			url: SecurityAPI,
			method: "POST",
			header: {
				"X-Token": access_token
			},
			data: {
				tasks: tasks
			},
			success: ({
				statusCode,
				data
			}) => {


				if (statusCode == 200) {
					let result = data.data
					resolve(result.some(item => item.predicts.some(i => i.hit)))
				}

			},
			fail: (err) => {
				reject(err)
			}
		})
	})

}